package com.yootk.servlet.handler;

import com.yootk.dbc.DatabaseConnection;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

public class ExportHandler {
    private Date beginDate;
    private Date endDate;

    public ExportHandler(Date beginDate, Date endDate) {
        this.beginDate = beginDate;
        this.endDate = endDate;
    }

    public String getData() {
        String data = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 定义内存流
        try {
            String sql = "SELECT device, intime, status FROM record WHERE intime BETWEEN ? AND ?";
            PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
            pstmt.setDate(1, new java.sql.Date(this.beginDate.getTime()));
            pstmt.setDate(2, new java.sql.Date(this.endDate.getTime()));
            ResultSet rs = pstmt.executeQuery(); // 数据查询
            Document document = DocumentHelper.createDocument();    // 创建一个空的文档
            Element infosElement = document.addElement("infos"); // 定义根元素
            while (rs.next()) {
                Element bookElement = infosElement.addElement("info");    // 创建子元素
                bookElement.addElement("device").setText(rs.getString(1));    // 设置子元素
                bookElement.addElement("intime").setText(String.valueOf(rs.getTimestamp(2).getTime()));    // 设置子元素
                bookElement.addElement("status").setText(String.valueOf(rs.getInt(3)));    // 设置子元素
            }
            XMLWriter writer = new XMLWriter(outputStream);	// XML文件输出
            writer.write(document); 					// 输出文档内容
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseConnection.close();
        }
        return outputStream.toString();
    }
}
